package org.springblade.modules.serial;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ChannelHandler.Sharable
public class SmartWriteTimeoutHandler extends ChannelInboundHandlerAdapter {
	private static final Logger logger = LoggerFactory.getLogger(SmartWriteTimeoutHandler.class);

	private static final ByteBuf HEARTBEAT = Unpooled.copiedBuffer("PING",CharsetUtil.UTF_8);
    private int timeoutCount = 0;
    private static final int MAX_TIMEOUT_COUNT = 3;

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.WRITER_IDLE) {
				logger.info("无心跳动返回");
				if (timeoutCount < MAX_TIMEOUT_COUNT) {
                    // 先发送心跳检测
                    ctx.writeAndFlush(HEARTBEAT.duplicate());
                    timeoutCount++;
                } else {
					logger.info("无心跳动返回则断开");
                    // 多次无响应后断开
                    ctx.close();
                }
            }
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // 收到任何消息都重置计数器
        timeoutCount = 0;
        ctx.fireChannelRead(msg);
    }
}
